package filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Permission;
import service.PermissionService;
import service.impl.PermissionServiceImpl;


public class AuthFilter implements Filter {
	
	private String[] ignorURL;
	
	public boolean isIgnore(HttpServletRequest request) {
		String path=request.getRequestURI().toLowerCase();
		for(String ignore:ignorURL) {
			if(path.contains(ignore)) {
				return true;
			}
		}
		return false;
	}
	
	private PermissionService permissionService = new PermissionServiceImpl(); 

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		if(isIgnore(request)){
			chain.doFilter(req, res);
			return;
		}
		
		String uri = request.getRequestURI();
		String path = request.getSession().getServletContext().getContextPath();
		
		List<Permission> permissions = permissionService.queryAll();
		Set<String> uriSet = new HashSet<String>();
		for ( Permission permission : permissions ) {
			if ( permission.getUrl() != null && !"".equals(permission.getUrl()) ) {
				uriSet.add(path + permission.getUrl());
			}
		}
		
		if (uriSet.contains(uri)) {
			Set<String> authUriSet = (Set<String>)request.getSession().getAttribute("authUriSet");
			if ( authUriSet.contains(uri) ) {
				chain.doFilter(request, response);
				return;
			} else {
				response.sendRedirect(path + "/error");
				return;
			}
		} 
		chain.doFilter(request, response);		
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.ignorURL = config.getInitParameter("ignorUrl").split(",");		
	}
}
